﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using Newtonsoft.Json;
using System.Net;
using System.IO;
using UcAsp.Net.Model;
using UcAsp.Net.BLL;
using System.Web;
namespace UcAsp.Net.OpenApi.QQ
{
    public class Api : BaseOpenApi
    {
        public string OpenID { get; set; }
        public override string Login()
        {
            return "https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=" + BLL.SysParamBLL.GetParamByName("QQAPPID") + "&redirect_uri=" + BLL.SysParamBLL.GetParamByName("QQRedirect") + "&scope=get_user_info,add_share,add_t,add_idol";
        }
        public override bool OpenApi(string Code)
        {
            try
            {
                Dictionary<string, string> param = new Dictionary<string, string>();
                param.Add("client_id", BLL.SysParamBLL.GetParamByName("QQAPPID"));
                param.Add("grant_type", "authorization_code");
                param.Add("client_secret", BLL.SysParamBLL.GetParamByName("QQAPPKEY"));
                param.Add("redirect_uri", BLL.SysParamBLL.GetParamByName("QQRedirect"));
                param.Add("code", Code);

                string logintext = HttpWebClient.PostString("https://graph.qq.com/oauth2.0/token", param);
                string[] str = logintext.Split('&');
                QQToken token = new QQToken { access_token = str[0].Split('=')[1], expires_in = int.Parse(str[1].Split('=')[1]), refresh_token = str[2].Split('=')[1] };
                string openid = HttpWebClient.GetString("https://graph.qq.com/oauth2.0/me?access_token=" + token.access_token + "").Replace("callback( ", "").Replace(" )", "");
                JsonReader json = new JsonTextReader(new StringReader(openid));
                JsonSerializer serializer = new JsonSerializer();
                Weibo.OpenID open = (Weibo.OpenID)serializer.Deserialize(json, typeof(Weibo.OpenID));
                string userinfo = HttpWebClient.GetString("https://graph.qq.com/user/get_user_info?access_token=" + token.access_token + "&oauth_consumer_key=" + BLL.SysParamBLL.GetParamByName("QQAPPID") + "&openid=" + open.openid + "");
                JsonReader userjson = new JsonTextReader(new StringReader(userinfo.Replace("\\", "").Replace("\n", "")));
                QQUser qquser = (QQUser)serializer.Deserialize(userjson, typeof(QQUser));
                OpenID = open.openid;
                WriteWeibo("http://www.ucasp.net", @"http://img01.taobaocdn.com/bao/uploaded/i1/14345027233690117/T1NkWtFeXcXXXXXXXX_!!0-item_pic.jpg_240x240.jpg", token.access_token);
                if (qquser != null)
                {

                    UserInfo user = new BLL.UserInfoBLL().GetUserInfoByNameAndOpenID(qquser.nickname, BLL.SysParamBLL.GetParamByName("QQAPPID"));
                    if (user == null)
                    {
                        int recommandid = 0;
                        if (HttpContext.Current.Request.Cookies["User"] != null)
                        {
                            recommandid = int.Parse(HttpContext.Current.Request.Cookies["User"]["UserID"].ToString());
                            UserInfo recomuser = new UserInfoBLL().GetUserInfoByID(recommandid);
                            recomuser.Point += int.Parse(SysParamBLL.GetParamByName("RecommendPoint"));
                            new BLL.UserInfoBLL().Update(recomuser);
                        }
                        user = new UserInfo { UserName = qquser.nickname, OpenID =open.openid, SessionID = token.access_token, Point = int.Parse(SysParamBLL.GetParamByName("Point")), LoginTime = DateTime.Now, Logo = qquser.figureurl_1, LoginIP = HttpContext.Current.Request.UserHostAddress, Remark = qquser.msg };
                        new BLL.UserInfoBLL().Insert(user);
                    }
                    else
                    {
                        TimeSpan ts = DateTime.Now - user.LoginTime;
                        double timespan = Math.Abs(ts.TotalDays);
                        if (timespan > 1)
                        {
                            user.Point += int.Parse(SysParamBLL.GetParamByName("PrePoint"));
                        }
                        user.LoginTime = DateTime.Now;
                        new BLL.UserInfoBLL().Update(user);
                    }
                    HttpContext.Current.Session["UserID"] = user.ID;
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch
            {
                return false;
            }
        }
        public override bool WriteWeibo(string content, string urlfile, string access_token)
        {
            content = content.Length > 140 ? content.Substring(0, 140) : content;
            Dictionary<object, object> param = new Dictionary<object, object>();
            param.Add("access_token", access_token);
            param.Add("oauth_consumer_key", BLL.SysParamBLL.GetParamByName("QQAPPKEY"));
            param.Add("openid", OpenID);
            param.Add("content", Uri.EscapeDataString(content)); 
          
           // param.Add("clientip", "60.176.7.145");//HttpContext.Current.Request.UserHostAddress
            
           
            
            byte[] pic = new WebClient().DownloadData(urlfile);
            HttpWebClient.HttpPost("https://graph.qq.com/t/add_pic_t", param, pic);
            return true;
        }
        public override bool AddFollow(string usernick, string access_token)
        {
            Dictionary<string, string> param = new Dictionary<string, string>();
            param.Add("name", BLL.SysParamBLL.GetParamByName("QQName"));
            param.Add("openid", access_token);
            param.Add("userip",HttpContext.Current.Request.UserHostAddress);
            param.Add("openkey", BLL.SysParamBLL.GetParamByName("QQAPPID"));
            HttpWebClient.PostString("http://openapi.tencentyun.com/v3/relation/add_idol", param);
            return true;

        }
    }
}
